<template>
  <div class="app-container">
    <h4 class="form-header h4">基本信息</h4>
    <el-form ref="form" :model="queryParams" label-width="80px">
      <el-row>
        <el-col :span="8" :offset="2">
          <el-form-item label="用户昵称" prop="nickName">
            <el-input v-model="queryParams.nickName" disabled/>
          </el-form-item>
        </el-col>
        <el-col :span="8" :offset="2">
          <el-form-item label="登录账号" prop="userName">
            <el-input v-model="queryParams.userName" disabled/>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div style="display: flex;justify-content: space-between;margin-bottom: 10px">
      <el-button type="primary" icon="el-icon-search" size="small" @click="handleList">选择仓库</el-button>
      <div>
        <el-button type="success" @click="submitForm()">提交</el-button>
        <el-button @click="close()">返回</el-button>
      </div>
    </div>
    <el-table :row-key="getRowKey" @row-click="clickRow" ref="tableList" @selection-change="handleSelectionChange"
              :data="warehouseList" >
      <el-table-column type="selection" :reserve-selection="true" width="55"></el-table-column>
      <el-table-column label="仓库ID" align="center" prop="warehouseId"/>
      <el-table-column label="仓库编码" align="center" prop="warehouseCode"/>
      <el-table-column label="仓库名称" align="center" prop="warehouseName"/>
      <el-table-column label="类型" align="center" prop="type"/>
      <el-table-column label="默认管理仓库" align="center" prop="isDefault">
        <template slot-scope="scope">
          <el-switch v-model="scope.row.isDefault"  :disabled="isDisabled"
                     @change="getCurrentRow($event,scope.row,scope.$index)"></el-switch>
        </template>
        </el-table-column>
    </el-table>
    <pagination v-show="total>0" :total="total" :page.sync="pageNum" :limit.sync="pageSize"/>
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" label-width="60px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="名称" prop="warehouseName">
              <el-input
                v-model="form.warehouseName"
                placeholder="请输入名称"
                clearable
                @keyup.enter.native="handleQuery"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item>
              <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
              <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <el-table :row-key="getRowKeyWarehouse" @row-click="clickRowWarehouse" ref="tableWarehouse"
                @selection-change="handleSelectionChangeDia"
                :data="warehouseData"
      >
        <el-table-column type="selection" :reserve-selection="true" width="55"></el-table-column>
        <el-table-column label="仓库ID" align="center" prop="warehouseId"/>
        <el-table-column label="仓库编码" align="center" prop="warehouseCode"/>
        <el-table-column label="仓库名称" align="center" prop="warehouseName"/>
        <el-table-column label="类型" align="center" prop="type"/>
      </el-table>
      <pagination
        v-show="totalDialog>0"
        :total="totalDialog"
        :page.sync="pageNumDialog"
        :limit.sync="pageSizeDialog"
        @pagination="getHouseList"
      />
      <el-form>
        <el-form-item style="text-align: center;margin-top:30px;">
          <el-button type="primary" @click="handleSubmit">确定</el-button>
          <el-button @click="backTo()">返回</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import { getAuthRole, getAuthWarehouse, handleWarehouse, updateAuthRole } from '@/api/system/user'
import { listWarehouse } from '@/api/system/warehouse'

export default {
  name: 'AuthWarehouse',
  data() {
    return {
      isDisabled:false,
      checkList:[],
      userId:'',
      templateRadio:[],
      warehouseDia: [],
      warehouseList: [],
      warehouseData: [],
      // 遮罩层
      loading: true,
      //彈出框
      totalDialog: 0,
      pageNumDialog: 1,
      pageSizeDialog: 10,
      // 分页信息
      total: 0,
      pageNum: 1,
      pageSize: 5,
      // 选中仓库编号
      warehouseIds: [],
      // 角色信息
      roles: [],
      // 用户信息
      form: {},
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      queryParams: {}
    }
  },
  created() {
    this.userId = this.$route.params && this.$route.params.userId
    if (this.userId) {
      getAuthWarehouse( this.userId).then((response) => {
        this.queryParams = response.user;
        this.warehouseList = response.warehouses;
        this.total = this.warehouseList.length;
        this.$nextTick(() => {
          this.warehouseList.forEach((row) => {
            if (row.warehouseId) {
              this.$refs.tableList.toggleRowSelection(row);
            }
          });
        });
      })
    }
  },
  methods: {
    //唯一值的确认。
    getCurrentRow(e,indexRadio,ind){
      this.warehouseList.map((item,index)=>{
        item.userId=this.userId
        if(index===ind ){
          item.isDefault=e;
          this.warehouseList[index] =item
        }else{
          item.isDefault=!e;
          this.warehouseList[index] =item;
        }
      })
    },
    //弹出框的确认按钮，将数据跟页面列表的数据，进行比较，筛除相同项。
    handleSubmit() {
      this.open = false;
      if (this.warehouseList) {//存在数组
        this.warehouseDia.map((item) => {
          this.warehouseList.push(item);
        })
        //筛选数据
        let len = this.warehouseList.length
        for (let i = 0; i < len; i++) {
          for (let j = i + 1; j < len; j++) {
            if (this.warehouseList[i].warehouseId === this.warehouseList[j].warehouseId) {
              this.warehouseList.splice(j, 1)
              len-- // 减少循环次数提高性能
              j-- // 保证j的值自加后不变
            }
          }
        }
      } else {
        this.warehouseList = this.warehouseDia
      }
    },
    backTo() {
      this.open = false;
      this.resetQuery()
    },
    getHouseList() {
      listWarehouse(this.form).then(response => {
        this.warehouseData = response.rows
        this.totalDialog = response.total
      })
    },
    // 多选框选中数据,弹出框
    handleSelectionChangeDia(selection) {
      this.warehouseDia = selection
    },
    clickRowWarehouse(row) {
      this.$refs.tableWarehouse.toggleRowSelection(row)
    },
    getRowKeyWarehouse() {
    },
    //选择仓库按钮,打开弹出框
    handleList() {
      this.open = true
      this.title = '选择仓库'
      this.getHouseList()
    },
    /** 单击选中行数据 */
    clickRow(row) {
      // this.$refs.tableList.toggleRowSelection(row)
    },
    // 多选框选中数据,页面
    handleSelectionChange(selection) {
      this.checkList =selection;
      for(let i = 0; i < this.checkList.length; i++){
        this.checkList[i].isDisabled =false;
      }
      for (let i = 0; i < this.warehouseList.length; i++) {
        for (let j = 0; j < this.checkList.length; j++) {
          if(this.warehouseList[i].warehouseId === this.checkList[j].warehouseId){
         this.warehouseList[i].isDisabled=false;
            this.checkList[j].isDisabled =false;
          }else{
            this.warehouseList[i].isDisabled =true;
          }
        }
      }
      this.checkList.map((item,index)=>{
        if(item==false) {
          this.warehouseList[index].isDisabled = false;
        }
      })
      this.warehouseIds=selection.map((item) => item.warehouseId);
    },
    // 保存选中的数据编号
    getRowKey(row) {
      return row.warehouseId;
    },
    handleQuery() {
      this.form.pageNum = 1
      this.getHouseList()
    },
    //重置
    resetQuery() {
      this.form = {}
    },
    /** 提交按钮 */
    submitForm() {
      let listSub=[];
      listSub =this.resultSameValue(this.warehouseList,this.checkList);
      listSub.map((item)=>{
        item.userId =this.userId
      })
      handleWarehouse(listSub).then((response) => {  this.$modal.msgSuccess('授权成功')
          this.close()
        })
    },
    //获取重复数据
    resultSameValue(arr1, arr2) {
      let newArr = [];
      for (let i = 0; i < arr1.length; i++) {
        if (arr2.includes(arr1[i])) {
          newArr.push(arr1[i])
        }
      }
      return newArr;
    },
    /** 关闭按钮 */
    close() {
      const obj = { path: '/system/user' }
      this.$tab.closeOpenPage(obj)
    }
  }
}
</script>
